#!/usr/bin/env python
#
#

# user config

datadir = 'data'

# end user config

from ommbot.world import rlog, enable_logging, enable_plugs, enable_fleet, \
                         mainhandler, get_plugs, get_fleet, enable_config, \
                         get_config, set_datadir
from ommbot.generic import die, handle_exception
from ommbot.bot import Bot
import ommbot.world
import os
import time
import sys
import signal

for i in sys.argv:
    if os.path.isdir(i):
        os.chdir(i)
        datadir = i

# stop function
def stop(x, y):
    try:
        get_fleet().exitall()
    except:
        pass
    try:
        get_plugs().exit()
    except:
        pass
    die()

# register SIGTERM handler to stop
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)

if not os.path.isdir(datadir):
    print 'no %s dir available as datadir' % datadir
    os._exit(1)

set_datadir(datadir)
enable_config(datadir)
config = get_config()

try:
    enable_logging(config['loglevel'])
    rlog(10, 'OMMBOT', 'STARTING %s' % config['version'])
    enable_plugs(datadir)
    bot = Bot('main', datadir, config['owner'])
    enable_fleet(bot, datadir)
    bot.start()
    bot.connect(config['nick'], config['server'], config['port'])
    bot.connected.wait()
    bot.joinchannels()
except Exception, ex:
    handle_exception()
    stop(0, 0)

while 1:
    try:
        time.sleep(1)
        mainhandler.handle_one()
    except KeyboardInterrupt:
        stop(0, 0)
    except Exception, ex:
        handle_exception()
        stop(0, 0)
